/**
 * @author yxw
 * date : 2013年9月30日 下午3:50:36 
 */
package com.tzinfo.tzb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.DefaultResult;
import com.tzinfo.tzb.domain.DiaryList;
import com.tzinfo.tzb.domain.Tzb_UserInfoModel;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.util.YXWImageFactory;
import com.yxw.view.NoScrollListView;
import com.yxw.view.YXWVerticalScrollView;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

public class TzbUserInfoActivity extends TzbBaseActivity {

	// 标志
	public static boolean isNeedReflash = false;
	public boolean isFans = false;
	// 数据
	private Tzb_UserInfoModel userInfoModel = null;
	private DiaryList diaryList = null;
	private int fansType = 1;
	private String username = null;

	// UI组件
	private ImageView img_touxiang;
	private TextView text_no_riji;
	private Button bt_guanzhu;
	private TextView[] infoTextView = new TextView[6];
	private NoScrollListView listView;
	private TextView text_gexingqianming;
	private LinearLayout layout_baby;
	private YXWVerticalScrollView verticalscrollview;

	// 适配器
	private ImageAdapter imageAdapter;

	public static TzbUserInfoActivity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		activity = this;
		setContentView(R.layout.tzb_ac_userinfo_page);
		initParameter();
		init();
		initData();
	}

	private void initParameter() {
		isFans = this.getIntent().getBooleanExtra("isFans", false);
		username = this.getIntent().getStringExtra("username");
		if (isFans) {
			fansType = 2;
		} else {
			fansType = 1;
		}
	}

	private void init() {
		layout_baby = (LinearLayout) ResFinder.findViewById(this,
				"R.id.layout_baby");
		text_no_riji = (TextView) ResFinder.findViewById(this,
				"R.id.text_no_riji");
		infoTextView[0] = (TextView) ResFinder.findViewById(this,
				"R.id.text_username");
		infoTextView[1] = (TextView) ResFinder.findViewById(this,
				"R.id.text_netname");
		infoTextView[2] = (TextView) ResFinder.findViewById(this,
				"R.id.text_userstate");
		infoTextView[3] = (TextView) ResFinder.findViewById(this,
				"R.id.text_ubirthday");
		infoTextView[4] = (TextView) ResFinder.findViewById(this,
				"R.id.text_bbsex");
		infoTextView[5] = (TextView) ResFinder.findViewById(this,
				"R.id.text_bbbirthday");
		text_gexingqianming = (TextView) ResFinder.findViewById(this,
				"R.id.text_gexingqianming");
		img_touxiang = (ImageView) ResFinder.findViewById(this,
				"R.id.img_touxiang");
		bt_guanzhu = (Button) ResFinder.findViewById(this, "R.id.bt_topbar_r1");
		listView = (NoScrollListView) ResFinder.findViewById(this,
				"R.id.listView");
		verticalscrollview = (YXWVerticalScrollView) ResFinder.findViewById(
				this, "R.id.verticalscrollview");
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (diaryList != null) {
					Intent intent = new Intent(TzbUserInfoActivity.this,
							TzbMyDirayDetailActivity.class);
					TzbCommonData.diaryItem = arg2;
					TzbUserInfoActivity.this.startActivityForResult(intent, 1);
				}
			}
		});

		// 设置圆角
		img_touxiang
				.setImageBitmap(YXWImageFactory.toRoundCorner(BitmapFactory
						.decodeResource(getResources(), ResFinder.getR(this,
								"R.drawable.tzb_no_touxiang")), 20));
	}

	public void initData() {
		// 设置用户信息
		getUserInfo();
		verticalscrollview.setVisibility(View.VISIBLE);
		dialog.show();
	}

	private void getUserInfo() {
		dialog.show();
		GalHttpRequest userInfoHttpRequest = new GalHttpRequest(this);
		userInfoHttpRequest.setCacheEnable(false);
		String url4 = ResFinder.getResString(this,
				"R.string.tzb_url_Tzb_UserInfoModel") + "?username=" + username;
		OutLog.LogE("yxw", "user:" + url4);
		userInfoHttpRequest.setURL(url4);
		userInfoHttpRequest
				.startAsynRequestString(new GalHttpLoadTextCallBack() {

					@Override
					public void textLoaded(String arg0) {
						Gson gson = new Gson();
						java.lang.reflect.Type type = new TypeToken<Tzb_UserInfoModel>() {
						}.getType();
						userInfoModel = gson.fromJson(arg0, type);
						removeProgressBar();
						if (userInfoModel.isSuccess()) {
							// 获取日志
							if (diaryList == null) {
								getRizhi();
							} else {
								setRijiUI();
							}
							OutLog.LogE("yxw", "touxiang:"
									+ userInfoModel.getData().getAvatar());
							text_gexingqianming.setText("个性签名："
									+ userInfoModel.getData().getSignature());
							imageLoader.displayImage(userInfoModel.getData()
									.getAvatar(), img_touxiang, options,
									new ImageLoadingListener() {

										@Override
										public void onLoadingStarted(
												String arg0, View arg1) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingFailed(
												String arg0, View arg1,
												FailReason arg2) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingComplete(
												String arg0, View arg1,
												Bitmap arg2) {
											// TODO Auto-generated method stub
											arg2 = YXWImageFactory
													.toRoundCorner(arg2, 20);

										}

										@Override
										public void onLoadingCancelled(
												String arg0, View arg1) {
											// TODO Auto-generated method stub

										}
									});
							imageLoader.displayImage(userInfoModel.getData()
									.getAvatar(), img_touxiang, options);
							setUserInfo();
						} else {
							Toast.makeText(TzbUserInfoActivity.this,
									userInfoModel.getMsg(), 1).show();
							dialog.dismiss();
							TzbUserInfoActivity.this.finish();
						}
					}
				});
	}

	private void setUserInfo() {
		if (userInfoModel != null && userInfoModel.getData() != null) {
			OutLog.LogE("yxw", userInfoModel.getData().getBbbirthday() + "");
			infoTextView[0].setText(userInfoModel.getData().getUsername());
			infoTextView[1].setText(userInfoModel.getData().getNetname());
			infoTextView[2].setText(userInfoModel.getData().getUserstate());
			if (!"有宝宝".equals(userInfoModel.getData().getUserstate())) {
				layout_baby.setVisibility(View.GONE);
			}
			String ubirthday = userInfoModel.getData().getUserbirthday();
			ubirthday = YXWDateUtil.getTimeformat(ubirthday,
					"MM/dd/yyyy HH:mm:ss", "yyyy-MM-dd");
			infoTextView[3].setText(ubirthday);
			infoTextView[4].setText(userInfoModel.getData().getBbsex());
			String bbbirthday = userInfoModel.getData().getBbbirthday();
			bbbirthday = YXWDateUtil.getTimeformat(bbbirthday,
					"MM/dd/yyyy HH:mm:ss", "yyyy-MM-dd");
			infoTextView[5].setText(bbbirthday);
		}
	}

	private void getRizhi() {
		GalHttpRequest rizhiHttpRequest = new GalHttpRequest(this);
		rizhiHttpRequest.setCacheEnable(false);
		String url = ResFinder.getResString(this, "R.string.tzb_url_DiaryList")
				+ "?username=" + userInfoModel.getData().getUsername()
				+ "&Page=1" + "&Pagesize=5";
		OutLog.LogE("yxw", "Rizhi:" + url);
		rizhiHttpRequest.setURL(url);
		rizhiHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DiaryList>() {
				}.getType();
				diaryList = gson.fromJson(arg0, type);
				if (diaryList != null && diaryList.isSuccess()
						&& diaryList.getData().size() > 0) {
					TzbCommonData.diaryList = diaryList;
					setRijiUI();
				} else {
					listView.setVisibility(View.GONE);
					text_no_riji.setVisibility(View.VISIBLE);
				}
				dialog.dismiss();
			}
		});
	}

	private void setRijiUI() {
		diaryList = TzbCommonData.diaryList;
		if (diaryList == null) {
			getRizhi();
			return;
		}
		listView.setVisibility(View.VISIBLE);
		text_no_riji.setVisibility(View.GONE);
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < diaryList.getData().size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			if (diaryList.getData().get(i).getPhoto().size() > 0) {
				String imageUil = diaryList.getData().get(i).getPhoto().get(0)
						.getPicfile();
				map.put("image", imageUil);
			} else {
				map.put("image", ResFinder.getR(this, "R.drawable.ic_empty"));
			}

			map.put("title", diaryList.getData().get(i).getTitle());
			String time = YXWDateUtil.getTimeByDayInterval(diaryList.getData()
					.get(i).getPtime(), "MM/dd/yyyy");
			map.put("time", time);
			map.put("username", diaryList.getData().get(i).getUsername());
			map.put("supports", diaryList.getData().get(i).getSupports());
			data.add(map);
		}
		imageAdapter = new ImageAdapter(this, data, ResFinder.getR(this,
				"R.layout.tzb_item_riji"), new String[] { "image", "title",
				"time", "username", "supports" }, new int[] {
				ResFinder.getR(this, "R.id.list_item_image"),
				ResFinder.getR(this, "R.id.list_item_title"),
				ResFinder.getR(this, "R.id.list_item_time"),
				ResFinder.getR(this, "R.id.list_item_netname"),
				ResFinder.getR(this, "R.id.list_item_supports") });
		listView.setAdapter(imageAdapter);
		removeProgressBar();
		dialog.dismiss();
	}

	// onclick
	public void onGuanzhu(View v) {
		if (TztData.userInfo == null) {
			Toast.makeText(this, "亲，请先登录才能使用该功能", 1).show();
			return;
		}
		if (TztData.userInfo.getData().getUserName()
				.equals(userInfoModel.getData().getUsername())) {
			Toast.makeText(this, "亲，不能关注自己哦！", 1).show();
			return;
		}
		// 关注
		String url = ResFinder.getResString(this, "R.string.tzb_url_UserFans")
				+ "?sessionid=" + TztData.userInfo.getData().getSessionID()
				+ "&fansuid=" + userInfoModel.getData().getUid() + "&fansname="
				+ userInfoModel.getData().getUsername() + "&type=" + fansType;
		OutLog.LogE("yxw", "url:" + url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
		galHttpRequest.setCacheEnable(false);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				OutLog.LogE("yxw", "json:" + arg0);
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
				}.getType();
				DefaultResult result = gson.fromJson(arg0, type);
				OutLog.LogE("yxw", "result:" + result.toString());
				dialog.dismiss();
				if (result.isSuccess()) {
					TzbTabMyActivity.isNeedReLoadNum = true;
					if (isFans) {
						Toast.makeText(TzbUserInfoActivity.this, "你取消了关注！", 0)
								.show();
						bt_guanzhu.setText("关注");
						isFans = false;
						fansType = 1;
					} else {
						Toast.makeText(TzbUserInfoActivity.this, "关注成功！", 0)
								.show();
						bt_guanzhu.setText("取消关注");
						isFans = true;
						fansType = 2;
					}
				}

			}
		});

	}

	// onclick
	public void goAllDirayList(View v) {
		Intent intent = new Intent(this, TzbDirayListActivity.class);
		intent.putExtra("username", userInfoModel.getData().getUsername());
		startActivity(intent);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void onReFlash() {
		OutLog.LogE("yxw", "onReFlash");
		if (isNeedReflash) {
			showProgressBar();
			getRizhi();
			isNeedReflash = false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		OutLog.LogE("yxw", "onActivityResult");
		if (requestCode == 1 && resultCode == 1) {
			boolean isNeedReflash = data.getBooleanExtra(TzbCommonData.IS_OK,
					false);
			if (isNeedReflash) {
				setRijiUI();
			}
		}
	}
}
